(function($) {
	var nurseID = '',maxRole;
	var doneArr = [],dealArr = [];
	var doneStart = 0,dealStart = 0,limit = 20;
	var thisMonthStr = '';
	var dealLoading = false;
	var doneLoading = false;
	var dealPullElement = null;	
	var donePullElement = null;
	var ymPicker
	$.init({
		swipeBack: true //启用右滑关闭功能
	});
	$.plusReady(function() {
		$('.mui-scroll-wrapper').scroll({
			indicators: false //是否显示滚动条
		});
		var _self = plus.webview.currentWebview();
		_self.setStyle({
			popGesture: 'none'  // 作用于ios 禁止右滑关闭
		});
		plus.navigator.setStatusBarBackground('#24af96');
		plus.navigator.setStatusBarStyle('light');
		mui.back = function() {
			plus.navigator.setStatusBarBackground('#fff')
			plus.navigator.setStatusBarStyle('dark');
			_self.close("auto");
		}
		
		var perInfo = app.getState()
		//console.log(JSON.stringify(perInfo));
		if(perInfo) {
			nurseID = perInfo.loginID;
			maxRole = perInfo.maxRoleLevel
		}
		
		mui(".mui-progressbar").each(function() {
			mui(this).progressbar({
				progress: this.getAttribute("data-progress")
			}).show();
		});
		tabInitAndTapSetup(); //tabbar 切换方法
		var scrolls = document.querySelectorAll('.mui-slider-group .mui-scroll');
		mui.each(scrolls,function(index, pullRefreshEl){
			mui(pullRefreshEl).pullToRefresh({
				up: {
					callback: function() {
						if (index == 0) {
							dealPullElement = this;
							getDealList();
						}else{
							donePullElement = this;
							getDoneList();
						}
					}
				}
			});
		});
		mui('#tab1Slider').slider().stopped = true;
		mui('#tab2Slider').slider().stopped = true;
		resetPullRefresh();
	});
	function getDealList(){
		if (dealLoading) {
			return;
		}
		getApproveList('dealWrapper');
	}
	
	function getDoneList(){
		if (doneLoading) {
			return;
		}
		getApproveList('doneWrapper');
	}

	function getApproveList(idStr) {
		var pageIndex = 0;
		var dealType = '';
		if(idStr == 'dealWrapper') {
			dealType = 'V';
			dealLoading = true;
			pageIndex = dealStart;
		} else if(idStr == 'doneWrapper') {
			dealType = 'R';
			doneLoading = true;
			pageIndex = doneStart;
		}
		var moreBtn = document.getElementById('moreBtn');
		var listType = moreBtn.getAttribute('data-type');
//		plus.nativeUI.showWaiting('正在加载',{modal:false});
		
		var startDate = document.getElementById('startDate');
		var currMonth = startDate.innerText
		var daysCount = getMonthMaxDay(currMonth);
		var stDateStr = currMonth + '-01';
		var endDateStr = currMonth + '-' + daysCount;
		
		//StDate(开始日期)^EndDate(结束日期)^nurseid(人员Id)^Type(类型)^Flag审批状态^maxRoleLevel最高级别
		var parr = stDateStr + '^' + endDateStr+'^'+nurseID+'^'+listType+'^'+dealType+'^'+maxRole
		var pdict = {'parr':parr,start: pageIndex,limit: limit}
		var paramDict = {'method':'web.INMOutInterface:FindNurHRapplicationList','params':JSON.stringify(pdict),'type':'RecQuery'}
		// console.log(JSON.stringify(pdict))
		mui.DHCWebService(paramDict, function(result) {
			plus.nativeUI.closeWaiting();
			// console.log(JSON.stringify(result)); 
			// console.log(result.data.length);
			if (result.msgcode != '1') {
				mui.toast(result.msg)
				if(idStr == 'dealWrapper') {
					if (dealPullElement != null) {
						dealPullElement.endPullUpToRefresh(false);
					}
					dealLoading = false;
				} else {
					if (donePullElement != null) {
						donePullElement.endPullUpToRefresh(false);
					}
					doneLoading = false;
				}	
				return;
			}
			var dataArr = result.data;
			if(idStr == 'dealWrapper') {
				dealArr = dealArr.concat(dataArr)
			} else {
				doneArr = doneArr.concat(dataArr)
			}
			updateTableView(dataArr,idStr);
			if (idStr == 'dealWrapper') {
				if (dealPullElement != null) {
					dealPullElement.endPullUpToRefresh(dataArr.length < limit);
				}
				dealLoading = false;
				dealStart += limit;
			}else if (idStr == 'doneWrapper') {
				if (donePullElement != null) {
					donePullElement.endPullUpToRefresh(dataArr.length < limit);
				}
				doneLoading = false;
				doneStart += limit;
			}
		}, function(errorStr) {
			mui.toast(errorStr);
			plus.nativeUI.closeWaiting();
			if(idStr == 'dealWrapper') {
				if (dealPullElement != null) {
					dealPullElement.endPullUpToRefresh(false);
				}
				dealLoading = false;
			} else {
				if (donePullElement != null) {
					donePullElement.endPullUpToRefresh(false);
				}
				doneLoading = false;
			}			
		});
	}

	function updateTableView(dataArr,idStr) {
		var tableUlId = 'dealUI';
		var currSeg = 0;
		if(idStr == 'doneWrapper') {
			tableUlId = 'doneUI';
			currSeg = 1;
		} 
		var tableUl = document.getElementById(tableUlId);
		var oldLength = tableUl.querySelectorAll('li').length;
		for(var i = 0; i < dataArr.length; i++) {
			var oneDict = dataArr[i];
			var oneLi = document.createElement('li');
			oneLi.setAttribute('class', 'mui-table-view-cell');
			oneLi.id = currSeg + '-' + (oldLength + i);
			tableUl.appendChild(oneLi);
			var AddDate = oneDict['CreateDate']||'';
			if (AddDate.length >= 10) {
				AddDate = AddDate.substr(5, 5)
			}
			var AddTime = oneDict['AddTime']||'';
			if (AddTime.length >= 5) {
				AddTime = AddTime.substr(0, 5)
			}
			var type = oneDict['Type']
			//专利PatValid 文章ArtValid 科研/课题 RecFlag
			var addDate = AddDate + '&nbsp;' + AddTime;
			var flag = oneDict['RecFlag']||'',flagDesc = oneDict['RecFlagDesc'];
			var src = '../../dependence/user/images/head.png'
			if (type == 'T') {//课题
				src = "../../dependence/wkplatform/images/ic_work_ky_04.png"
			}else if (type == 'SS') { //科研
				src = "../../dependence/wkplatform/images/ic_work_ky_02.png"
			}else if (type == 'P') {
				flag = oneDict['PatValid'];
				flagDesc = oneDict['PatValidDesc'];
				src = "../../dependence/wkplatform/images/ic_work_ky_07.png"
			}else if (type == 'A') {
				flag = oneDict['ArtValid'];
				flagDesc = oneDict['ArtValidDesc'];
				src = "../../dependence/wkplatform/images/ic_work_ky_01.png"
			}else if (type == 'W') {
				src = "../../dependence/wkplatform/images/ic_work_user_11.png"
			}else if (type == 'C') {
				src = "../../dependence/wkplatform/images/ic_work_ky_06.png"
			}
			
			var stateClass = '';
			// console.log(flag)
			//未审核Y 护士长审核通过A  护理部审核通过R   作废N  驳回B
			if(flag == 'Y') {
				stateClass = '';
			} else if(flag == 'A') { 
				stateClass = 'nurPassed';
			}else if (flag == 'R') {
				stateClass = 'passed';
			}else if (flag == 'N') {
				stateClass = 'unValid';
			} else if(flag == 'B') {
				stateClass = 'refused'
			}
			// console.log(flag)
			var html = '';
			if (type == 'SS') {//科研获奖
				html = '<div class="icon"><img src="'+src+'" /></div>'+
					'<div class="applyTitle">科研获奖</div><div class="applyContent">'+
					'<div class="label">奖项名称：</div><div class="labelKey bookName">'+
						oneDict['ScienName']+'</div><div></div>'+
					'<div class="label">完成人：</div><div class="labelKey">'+'1.'+oneDict['ScienFirPerDesc']+
						'、2.'+oneDict['ScienSecPerDesc']+'、3.'+oneDict['ScienThirdPerDesc']+'</div><div></div>'+
					'<div class="label">获奖日期：</div><div class="labelKey">'+
						oneDict['ScienDate']+'</div></div></div>';
			}else if (type == 'T') {//课题立项
				html = '<div class="icon"><img src="'+src+'" /></div>'+
					'<div class="applyTitle">课题立项</div><div class="applyContent">'+
					'<div class="label">课题名称：</div><div class="labelKey bookName">'+
						oneDict['ProjectName']+'</div><div></div>'+
					'<div class="label">负责人：</div><div class="labelKey">'+'1.'+oneDict['FirstResponserDesc']+
						'、2.'+oneDict['SecondResponserDesc']+'、3.'+oneDict['ThirdResponserDesc']+'</div><div></div>'+
					'<div class="label">立项日期：</div><div class="labelKey">'+
						oneDict['ProjectDate']+'</div></div></div>';
			}else if (type == 'P') {//护理专利
				var firStr = oneDict['PatFirInventorDesc']||'';
				if (firStr == '' && oneDict['PatFirInventor'] != '') {
					firStr = oneDict['PatFirInventor']
				}
				var appDate = oneDict['PatAppDate']?oneDict['PatAppDate']:""
				html = '<div class="icon"><img src="'+src+'" /></div>'+
					'<div class="applyTitle">护理专利</div><div class="applyContent">'+
					'<div class="label">专利名称：</div><div class="labelKey bookName">'+oneDict['PatName']+'</div><div></div>'+
					'<div class="label">发明人：</div><div class="labelKey">'+'1.'+firStr+'、2.'+oneDict['PatSecInventorDesc']+'、3.'+oneDict['PatThiInventorDesc']+'</div><div></div>'+
					'<div class="label">发明申请日：</div><div class="labelKey">'+appDate+'</div></div></div>';
			}else if (type == 'A') {//文章
				html = '<div class="icon"><img src="'+src+'" /></div>'+
					'<div class="applyTitle">文章上报</div><div class="applyContent">'+
					'<div class="label">文章名称：</div><div class="labelKey bookName">'+oneDict['ArtTitle']+'</div><div></div>'+
					'<div class="label">'+(oneDict['ArtAuthorTypeDesc']||'')+'：</div><div class="labelKey">'+oneDict['ArtFirAuthor']+'</div><div></div>'+					
					'<div class="label">发表日期：</div><div class="labelKey">'+oneDict['ArtDate']+'</div></div></div>'
			}else if (type == 'W') {//著作
				// console.log(JSON.stringify(oneDict))
				html = '<div class="icon"><img src="'+src+'" /></div>'+
					'<div class="applyTitle">著作</div><div class="applyContent">'+
					'<div class="label">书名：</div><div class="labelKey bookName">'+oneDict['BookName']+'</div><div></div>'+
					'<div class="label">作者姓名：</div><div class="labelKey">'+oneDict['AuthorDesc']+'</div><div></div>'+	
					'<div class="label">创建日期：</div><div class="labelKey">'+oneDict['CreateDate']+ '&nbsp' +oneDict['CreateTime']+'</div></div></div>'
			}else if (type == 'C') {//成果转化
				var firStr = oneDict['FirstPerDesc']||'';
				var secdStr = oneDict['SecPerDesc']||'';
				var thirdStr = oneDict['ThirdPerDesc']||'';
				html = '<div class="icon"><img src="'+src+'" /></div>'+
					'<div class="applyTitle">成果转化</div><div class="applyContent">'+
					'<div class="label">成果名称：</div><div class="labelKey bookName">'+oneDict['WorkName']+'</div><div></div>'+
					'<div class="label">完成人：</div><div class="labelKey">'+'1.'+firStr+'、2.'+secdStr+'、3.'+thirdStr+'</div><div></div>'+
					'<div class="label">创建日期：</div><div class="labelKey">'+oneDict['CreateDate']+ '&nbsp' +oneDict['CreateTime']+'</div></div></div>'
			}
			oneLi.innerHTML = html+'<div class="statetip '+stateClass+'">'+flagDesc+'</div>'+
				'<div class = "applyTime">'+addDate+'</div>';
		}
	}

	function openApplyDetailPage() {
		var idArr = this.id.split('-');
		var seg = parseInt(idArr[0]);
		var index = parseInt(idArr[1]);
		var oneDict;
		var fromPage = 'person-info'
		if(seg == 0) {
			fromPage = ''
			oneDict = dealArr[index];
		} else {
			oneDict = doneArr[index];
		}
		if(oneDict == null) {
			return;
		}
		// console.log(JSON.stringify(oneDict))
		var applyType = oneDict['Type'];
		var type = ''
		if (applyType == 'SS') {
			type = 'award'
		}else if (applyType == 'T') {
			type = 'topic'
		}else if (applyType == 'P') {
			type = 'patent'
		}else if (applyType == 'A') {
			type = 'artical'
		}else if (applyType == 'W') {
			type = 'work'
		}else if (applyType == 'C') {
			type = 'trans'
		}
		// console.log(JSON.stringify(oneDict));
		var detail = mui.openWindow({
			url:'../personInfo/book-detail.html',
			id:'book-detail',
			extras:{
				pageData:oneDict,
				applyType:applyType,
				type:type,
				fromPage:fromPage
			}
		});
		detail.addEventListener('close',function(){
			var detail = plus.storage.getItem('detail');
			if (detail == '1') {
				resetPullRefresh();
			}
		});
	}
	
	function selectAbsentMonth() {
		var _self = this;
		if(_self.picker) {
			_self.picker.show(function(rs) {
				_self.innerText = rs.text;
				_self.picker.dispose();
				_self.picker = null;
				resetPullRefresh();
			});
		} else {
			var optionsJson = '{"type":"month"}';
			var options = JSON.parse(optionsJson);
			_self.picker = new mui.DtPicker(options);
			_self.picker.show(function(rs) {
				_self.innerText = rs.text;
				_self.picker.dispose();
				_self.picker = null;
				resetPullRefresh();
			});
		}
	}
	function iosSelectAbsentMonth() {
		var btnDom = this
		ymPicker.show(function(items) {
			btnDom.innerText = items[0]['text']+'-'+items[1]['text'];
			resetPullRefresh();
		});
	}

	function resetPullRefresh(index) {
		if (index != 1) {
			mui('#dealUI').off('tap','li',openApplyDetailPage)
			mui('#dealUI')[0].innerHTML = '';
			mui('#dealUI').on('tap','li',openApplyDetailPage)
			dealStart = 0;
			dealArr.splice(0,dealArr.length);
			mui('#dealWrapper').scroll().scrollTo(0,0,100)
			if (dealPullElement) {
				dealPullElement.refresh(true);
			}
			getDealList();
		}
		if (index != 0) {
			mui('#doneUI').off('tap','li',openApplyDetailPage)
			mui('#doneUI')[0].innerHTML = '';
			mui('#doneUI').on('tap','li',openApplyDetailPage)
			doneStart = 0
			doneArr.splice(0, doneArr.length);
			mui('#doneWrapper').scroll().scrollTo(0,0,100);
			if (donePullElement) {
				donePullElement.refresh(true);
			}
			getDoneList();
		}
		
	}

	function tabInitAndTapSetup() {
		var today = getTodayStr();
		thisMonthStr = today.substring(0,today.length - 3);
		var startDate = document.getElementById('startDate');
		startDate.innerText = thisMonthStr;
		if (plus.os.name == 'iOS') {
			ymPicker = new mui.xhPicker(2,'请选择月份','pickerId2');
			var dateArr = []
			var monArr = []
			for (var i = 0; i < 12; i++) {
				var text = (i+1)
				if (text < 10) {
					text = '0'+text
				}
				monArr[i] = {'text':text}
			}
			var yearInt = new Date().getFullYear()-5;
			for (var i = 0; i < 11; i++) {
				dateArr[i] = {'text':yearInt+i,'children':monArr}
			}
			ymPicker.setData(dateArr);
			startDate.addEventListener('tap', iosSelectAbsentMonth, false);
		}else{
			startDate.addEventListener('tap', selectAbsentMonth, false);
		}
		var thisMonth = document.getElementById('thisMonth');
		thisMonth.addEventListener('tap', function() {
			var startDate = document.getElementById('startDate');
			startDate.innerText = thisMonthStr;
			resetPullRefresh();
		}, false);
		var lastMonth = document.getElementById('lastMonth');
		lastMonth.addEventListener('tap',function(){
			var startDate = document.getElementById('startDate');
			startDate.innerText = getFullLastMonth(startDate.innerText);
			resetPullRefresh();
		});
		var nextMonth = document.getElementById('nextMonth');
		nextMonth.addEventListener('tap',function(){
			var startDate = document.getElementById('startDate');
			startDate.innerText = getFullNextMonth(startDate.innerText);
			resetPullRefresh();
		});
		
		var tab1 = document.getElementById('tab1');
		var tab2 = document.getElementById('tab2');
		var tab1Content = document.getElementById('tab1Content');
		var tab2Content = document.getElementById('tab2Content');

		tab1.addEventListener('tap', function() {
			if(!tab1.classList.contains('mui-active')) {
				tab2Content.classList.remove('mui-active');
				tab2Content.style.display = 'none';
				tab1Content.classList.add('mui-active');
				tab1Content.style.display = 'block';
				if(dealArr == null) {
					if (dealPullElement) {
						dealPullElement.refresh(true);
					}
					getDealList();
				}
			}
		});
		tab2.addEventListener('tap', function() {
			if(!tab2Content.classList.contains('mui-active')) {
				tab1Content.classList.remove('mui-active');
				tab1Content.style.display = 'none';
				tab2Content.classList.add('mui-active');
				tab2Content.style.display = 'block';
				if(doneArr == null) {
					if (donePullElement) {
						donePullElement.refresh(true);
					}
					getDoneList();
				}
			}
		});
		var moreBtn = document.getElementById('moreBtn');
		var allE = document.getElementById('item-all')
		moreBtn.setAttribute('data-type',allE.getAttribute('data-type'));
		moreBtn.addEventListener('tap', function() {
			mui('#catePopover').popover('toggle', this);
		});
		var moreBtn2 = document.getElementById('moreBtn2');
		moreBtn2.addEventListener('tap', function() {
			mui('#catePopover').popover('toggle', this);
		});

		var catePopover = document.getElementById('catePopover');
		var items = catePopover.querySelectorAll('.mui-popover-item');
		for(var i = 0; i < items.length; i++) {
			var oneItem = items[i];
			oneItem.addEventListener('tap', function() {
				var type = this.getAttribute('data-type');
				var img = this.querySelector('img')
				var moreBtn = document.getElementById('moreBtn');
				var moreBtn2 = document.getElementById('moreBtn2');
				if(img) {
					moreBtn2.src = img.src;
					moreBtn.style.display = 'none';
					moreBtn2.style.display = 'block';
				} else {
					moreBtn2.style.display = 'none';
					moreBtn.style.display = 'block';
				}
				moreBtn.setAttribute('data-type', type);
				resetPullRefresh()
				mui('#catePopover').popover('toggle');
			}, false);
		}
	}
	/*
	 *  
		<li class="mui-table-view-cell" data-apply="book">
			<div class = "applyTitle" >张薇薇的个人资料(书籍) </div>
			<div class = "applyTime" >06-27 16: 11</div>
			<div class="label">出版日期：</div>
			<div class="labelKey amKey">2019-05-01</div><br/>
			<div class="label">发明专利：</div>
			<div class="labelKey amKey">2019-05-01</div><br/>
			<div class="label">出版社：</div>
			<div class="labelKey amKey">东华软件股份公司</div><br/>
			<div class="label">书籍名称：</div>
			<div class="labelKey amKey">论护理管理的重要性(第一版)</div><br/>
			<div class = "label" >出版日期： < /div>
			<div class = "labelKey" >发明专利 < /div><br / >
			<div class = "label" >出版社： < /div>
			<div class = "labelKey amKey"> 东华软件股份公司</div> <br / >			<			div class = "label" > 书籍名称： < /div> <			div class = "labelKey amKey" >			论护理管理的重要性(第一版) <			/div> <			div class = "statetip unpassed" > 已拒绝 < /div> <			/li> 
			
			<			li class = "mui-table-view-cell"
data - apply = "topic" >			<			div class = "applyTitle" > 张薇薇的个人资料(课题) < /div> <
	div class = "applyTime" > 06 - 27 16: 11 < /div> <
	div class = "label" > 课题级别： < /div> <
	div class = "labelKey" > 国家级课题 < /div> <
	br / >

	*/

})(mui);